// pages/IndexPage.js
import React from 'react';
import {
  Grid,
  useMediaQuery,
  useTheme,
  Box
} from '@mui/material';
import TopIcons from 'components/organisms/TopIcons';
import Footer from 'components/organisms/Footer';
import { AdaptiveLayoutLarge } from 'components/elements/AdaptiveLayout';
import { useDarkMode } from 'contexts/DarkMode';
import { useLocation } from 'react-router-dom';
import { RealEstatePageReveal } from 'components/molecules/RealEstatePageReveal';
import {
  HeroSection,
  FormHeaderSection,
  FormContactSection,
  FormPersonalSection,
  FormOwnerSection,
  FormPropertySection,
  FormAdditionalSection,
  FormSubmitSection,
  FormSuccessSection,
  BenefitsSection,
  DisclaimerSection,
  getDefaultStyles
} from './RealEstatePageComponent';
import PhotoCameraIcon from '@mui/icons-material/PhotoCamera';
import FlashOnIcon from '@mui/icons-material/FlashOn';
import HomeIcon from '@mui/icons-material/Home';
import AccountBalanceIcon from '@mui/icons-material/AccountBalance';
import PriceCheckIcon from '@mui/icons-material/PriceCheck';
import SequentialBackgroundIcons from 'components/electrons/SequentialBackgroundIcons';
import { DEFAULT_HOW_OPTIONS } from 'components/ui/Constants';
import useMlsFormSubmissionComplete from './use-mls-form-submission-complete';
import {
  MLS_DB_HOST,
  MLS_DB_NAME,
  MLS_DB_TABLE,
  MLS_DB_USERNAME,
  MLS_DB_PASSWORD
} from 'config/index';
import VisitorCounter from 'components/electrons/VisitorCounter';

const IndexPage = () => {
  const { darkMode } = useDarkMode();
  const isXs = useMediaQuery('(max-width:600px)');
  const location = useLocation();
  const isHomePage = location.pathname === '/';
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down('sm'));
  
  const styles = getDefaultStyles(isMobile);
  
  const useBorder = true;
  const useColor = '#f5f5f5';
  const useSize = 'small';
  const useButtonSize = 'medium';
  const useMiddle = false;
  const showBackgroundIcons = true;
  const defaultSameAddress = false;
  const sectionOrder = ['contact', 'personal', 'owner', 'property', 'additional'];
  const howOptions = DEFAULT_HOW_OPTIONS;
  
  const [formData, setFormData] = React.useState({
    cEmail: '',
    cPhone: '',
    cFax: '',
    cHow: howOptions[0],

    cBillFname: '',
    cBillLname: '',
    cBillCompany: '',
    
    cBillAddress1: '',
    cBillAddress2: '',
    cBillCity: '',
    cBillState: '',
    cBillZip: '',
    bill_county: '',
    cBillCountry: 'USA',
    
    billEqualShip: defaultSameAddress ? 'Y' : 'N',
    
    cShipCompany: '',
    cShipFname: '',
    cShipLname: '',
    cShipAddress1: '',
    cShipAddress2: '',
    cShipCity: '',
    cShipState: '',
    cShipZip: '',
    ship_county: '',
    cShipCountry: 'USA',
    
    cMemo: '',
    cPass: '',
    cPassHint: '',
    cWholesaleDiscount: null
  });

  const [errors, setErrors] = React.useState({});
  const { submitForm, submitting, submitSuccess, resetSubmission } = useMlsFormSubmissionComplete({
    dbHost: MLS_DB_HOST,
    dbName: MLS_DB_NAME,
    dbTable: MLS_DB_TABLE,
    dbUsername: MLS_DB_USERNAME,
    dbPassword: MLS_DB_PASSWORD
  });
  
  const backgroundIcons = [
    HomeIcon,
    PhotoCameraIcon,
    FlashOnIcon,
    AccountBalanceIcon,
    PriceCheckIcon
  ];

  React.useEffect(() => {
    if (defaultSameAddress) {
      setFormData(prevData => ({
        ...prevData,
        billEqualShip: 'Y'
      }));
    } else {
      setFormData(prevData => ({
        ...prevData,
        billEqualShip: 'N'
      }));
    }
  }, [defaultSameAddress]);

  const handleChange = (e) => {
    const { name, value, type, checked } = e.target;
    setFormData(prevData => ({
      ...prevData,
      [name]: type === 'checkbox' ? (checked ? 'Y' : 'N') : value
    }));

    if (name === 'billEqualShip' && checked) {
      setFormData(prevData => ({
        ...prevData,
        cShipAddress1: prevData.cBillAddress1,
        cShipAddress2: prevData.cBillAddress2,
        cShipCity: prevData.cBillCity,
        cShipState: prevData.cBillState,
        cShipZip: prevData.cBillZip,
        ship_county: prevData.bill_county,
        cShipCountry: prevData.cBillCountry,
        cShipFname: prevData.cBillFname,
        cShipLname: prevData.cBillLname,
        cShipCompany: prevData.cBillCompany
      }));
    }

    if (errors[name]) {
      setErrors(prev => ({ ...prev, [name]: '' }));
    }
  };

  const validate = () => {
    const newErrors = {};
    
    if (!formData.cEmail) {
      newErrors.cEmail = 'Email is required';
    } else if (!/\S+@\S+\.\S+/.test(formData.cEmail)) {
      newErrors.cEmail = 'Email is invalid';
    }
    if (!formData.cPhone) newErrors.cPhone = 'Phone number is required';
    if (!formData.cHow) newErrors.cHow = 'Please select how you heard about us';
    
    if (!formData.cBillFname) newErrors.cBillFname = 'First name is required';
    if (!formData.cBillLname) newErrors.cBillLname = 'Last name is required';
    
    if (!formData.cBillAddress1) newErrors.cBillAddress1 = 'Address is required';
    if (!formData.cBillCity) newErrors.cBillCity = 'City is required';
    if (!formData.cBillState) newErrors.cBillState = 'State is required';
    if (!formData.cBillZip) newErrors.cBillZip = 'ZIP code is required';
    
    if (formData.billEqualShip === 'N') {
      if (!formData.cShipFname) newErrors.cShipFname = 'Property owner first name is required';
      if (!formData.cShipLname) newErrors.cShipLname = 'Property owner last name is required';
      if (!formData.cShipAddress1) newErrors.cShipAddress1 = 'Property address is required';
      if (!formData.cShipCity) newErrors.cShipCity = 'Property city is required';
      if (!formData.cShipState) newErrors.cShipState = 'Property state is required';
      if (!formData.cShipZip) newErrors.cShipZip = 'Property ZIP code is required';
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    
    if (validate()) {
      console.log('Form data submitted:', formData);
      
      submitForm(formData).then(success => {
        if (success) {
          setFormData({
            cEmail: '',
            cPhone: '',
            cFax: '',
            cHow: howOptions[0],
            cBillFname: '',
            cBillLname: '',
            cBillCompany: '',
            cBillAddress1: '',
            cBillAddress2: '',
            cBillCity: '',
            cBillState: '',
            cBillZip: '',
            bill_county: '',
            cBillCountry: 'USA',
            billEqualShip: defaultSameAddress ? 'Y' : 'N',
            cShipCompany: '',
            cShipFname: '',
            cShipLname: '',
            cShipAddress1: '',
            cShipAddress2: '',
            cShipCity: '',
            cShipState: '',
            cShipZip: '',
            ship_county: '',
            cShipCountry: 'USA',
            cMemo: '',
            cPass: '',
            cPassHint: '',
            cWholesaleDiscount: null
          });
        }
      });
    } else {
      console.log('Form has errors:', errors);
    }
  };

  const textFieldStyle = {
    backgroundColor: useColor,
    '& .MuiOutlinedInput-root': {
      '& fieldset': {
        borderColor: useBorder ? 'rgba(0, 0, 0, 0.23)' : 'transparent',
      },
    },
    marginBottom: '8px',
  };

  const sectionHeaderStyle = {
    fontSize: '0.9rem',
    fontWeight: 'bold',
    marginBottom: '8px',
    marginTop: '16px',
    color: 'primary.main',
    position: 'relative',
    zIndex: 2,
  };
  
  const formSectionProps = {
    formData,
    handleChange,
    errors,
    textFieldStyle,
    sectionHeaderStyle,
    useSize,
    howOptions,
  };

  return (
    <>
      <Grid 
        item 
        xs={12} 
        sx={{ 
          display: 'flex', 
          justifyContent: 'center',
          width: '100%'
        }}
      >
        <AdaptiveLayoutLarge
          backgroundColor={null}
          backgroundColorInner={null}
          marginY={0}
          paddingY={0}
          paddingX={0}
          centered={true}
          fullWidth={true}
          useInnerWrapper={true}
        >
          <RealEstatePageReveal
            direction="left"
            useInnerBox={true}
            text={
              <>
                <TopIcons 
                  isXs={isXs} 
                  isHomePage={isHomePage} 
                  useTheme={false} 
                />
                <HeroSection 
                  headerTextStyle={styles.headerTextStyle}
                  subheaderTextStyle={styles.subheaderTextStyle}
                />
                <FormHeaderSection />
              </>
            }
          />

          {showBackgroundIcons && (
            <SequentialBackgroundIcons 
              icons={backgroundIcons}
              opacity={0.08}
              color="#1976d2"
              maxWidth="500px"
            />
          )}
            
          {!submitSuccess ? (
            <form onSubmit={handleSubmit} style={{ width: '100%', maxWidth: '800px' }}>
              <RealEstatePageReveal
                direction="left"
                useInnerBox={true}
                text={<FormContactSection {...formSectionProps} />}
              />
              
              <RealEstatePageReveal
                direction="right"
                useInnerBox={true}
                text={<FormPersonalSection {...formSectionProps} />}
              />
              
              <RealEstatePageReveal
                direction="left"
                useInnerBox={true}
                text={<FormOwnerSection {...formSectionProps} />}
              />
              
              <RealEstatePageReveal
                direction="right"
                useInnerBox={true}
                text={<FormPropertySection {...formSectionProps} />}
              />
              
              <RealEstatePageReveal
                direction="left"
                useInnerBox={true}
                text={<FormAdditionalSection {...formSectionProps} />}
              />
              
              <RealEstatePageReveal
                direction="right"
                useInnerBox={true}
                text={
                  <>
                    <FormSubmitSection 
                      submitting={submitting}
                      useButtonSize={useButtonSize}
                    />
                    <BenefitsSection 
                      headerTextStyle={styles.headerTextStyle}
                      bulletPointStyle={styles.bulletPointStyle}
                      smallTextStyle={styles.smallTextStyle}
                    />
                  </>
                }
              />
            </form>
          ) : (
            <RealEstatePageReveal
              direction="right"
              useInnerBox={true}
              text={
                <>
                  <FormSuccessSection 
                    resetSubmission={resetSubmission}
                    useButtonSize={useButtonSize}
                  />
                  <BenefitsSection 
                    headerTextStyle={styles.headerTextStyle}
                    bulletPointStyle={styles.bulletPointStyle}
                    smallTextStyle={styles.smallTextStyle}
                  />
                </>
              }
            />
          )}

          <RealEstatePageReveal
            direction="left"
            useInnerBox={true}
            text={
              <>
                <DisclaimerSection 
                  smallTextStyle={styles.smallTextStyle}
                />
                <VisitorCounter 
                  display={true} 
                  height={125}
                  useBackground={false}
                  useBorder={false}
                />
              </>
            }
          />
          
          <Footer 
            display={true}
            paddingY={2}
            paddingX={0}
          />
        </AdaptiveLayoutLarge>
      </Grid>
    </>
  );
};

export default IndexPage;